import React, { useState, useEffect, useContext } from "react";
import { useParams } from "react-router-dom";
import { AppState } from "../App";
import "../css/details.css";

const Usdetails = () => {
  const App = useContext(AppState);
  const { id } = useParams();
  const [requestData, setRequestData] = useState(null);
  const [donors, setDonors] = useState([]);
  const [donationAmounts, setDonationAmounts] = useState([]);
  const [currentAddress, setCurrentAddress] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        const request = await App.Foundationcontract.userrequestions(id);
        setRequestData(request);
        const [donors, amounts] =
          await App.Foundationcontract.getRequestDonations(id);
        setDonors(donors);
        setDonationAmounts(amounts);
      } catch (error) {
        console.error("Error fetching request data:", error);
      }
    };

    if (App.Foundationcontract && id) {
      fetchData();
    }
  }, [App.Foundationcontract, id, currentAddress]);

  useEffect(() => {
    const getAddress = async () => {
      try {
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        setCurrentAddress(accounts[0]);
      } catch (error) {
        console.error("Error fetching current account address:", error);
      }
    };

    getAddress();
  }, []);

  return (
    <div>
      <div className="headerContent"></div>
      {requestData && (
        <div className="detailDiv">
          <div className="image-container">
            <h1>{requestData.description}</h1>
            <img
              src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${requestData.photo}`}
              alt="Donation Image"
            />
          </div>
          <div className="record">
            <div className="donation-info">
              <h2>捐款记录</h2>
              <ul>
                {donors.length > 0 ? (
                  donors.map((donor, index) => (
                    <li
                      key={index}
                    >{`${donor} - ${donationAmounts[index]} WEI`}</li>
                  ))
                ) : (
                  <li>暂无捐款记录</li>
                )}
              </ul>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Usdetails;
